package tgc.rj.garbage;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import tgc.rj.garbage.custom.ToastUtils;
import tgc.rj.garbage.entity.AisleEntity;
import tgc.rj.garbage.utlis.AisleUtils;
import tgc.rj.garbage.utlis.FilesUtils;
import tgc.rj.garbage.utlis.Msg;
import tgc.rj.garbage.utlis.Queue;
import tgc.rj.garbage.utlis.SerialportCkUtils;

public class CanyuActivity extends AppCompatActivity implements Runnable {
    private Integer type;   //垃圾袋类型
    private String code = "";//二维码内容
    private boolean flag = true;
    private static byte txh;
    private Integer num;
    private SerialportCkUtils ckUtils;
    private ImageView imgage_jieshao;
    private TextView wzjs, btn2;
    private SharedPreferences txhs,sz;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_canyu);
        txhs = this.getSharedPreferences("txhs", MODE_PRIVATE);
        sz = this.getSharedPreferences("jcsz", MODE_PRIVATE);
        SharedPreferences.Editor edit = txhs.edit();
        Integer str1 = txhs.getInt("txhs", 1);
        txh = str1.byteValue();
        wzjs = findViewById(R.id.wzjs);
        imgage_jieshao = findViewById(R.id.image_jieshao);
        btn2 = findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        type = extras.getInt("type");
        if (type == 1) {
            imgage_jieshao.setImageResource(R.drawable.jieshaop);
            wzjs.setText("   该垃圾袋用于投放菜叶、剩菜、剩饭、果皮、蛋壳、茶渣、骨头等厨房垃圾");
        } else if (type == 2) {
            imgage_jieshao.setImageResource(R.drawable.qita);
            wzjs.setText("      该垃圾袋用于投放宠物粪便、烟头、污染纸张、灰土、一次性餐具等垃圾");
        }
    }

    /***
     * 开启出货线程
     */
    @Override
    public void run() {
        Queue.empty();
        while (flag) {
            String openId = Queue.pop();
            if (openId != null) {
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("data", openId);
                message.setData(bundle);
                this.handler.sendMessage(message);
            }
        }
    }

    /***
     * 取用户openId
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            flag = false;
            String openId = msg.getData().getString("data");
            AisleEntity model = AisleUtils.getFirst(type);
            num = model.getNum();
            code = model.getCode();
            sendHttp(type, openId);
        }
    };

    /**
     * 是否发袋验证
     * 请求名：weixin/qrfd
     * 发送http请求方法
     */
    private void sendHttp(final Integer type, final String openId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                String urls = sz.getString("url","https://baiyao.51baiyao.com");
                String urlStr = urls+"/gsm/weixin/qrfd";
                String jqbh = sz.getString("name","");

                try {
                    URL url = new URL(urlStr);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestMethod("POST");
                    String jqbhStr = URLEncoder.encode(jqbh, "UTF-8");
                    String paramStr = "openId=" + openId.trim() + "&ljdbh=" + code + "&jqbh=" + jqbhStr;
                    OutputStream out = conn.getOutputStream();
                    DataOutputStream dataOut = new DataOutputStream(out);
                    dataOut.writeBytes(paramStr);
                    dataOut.flush();
                    dataOut.close();
                    InputStream in = conn.getInputStream();
                    final String reponse = FilesUtils.readInfo(in);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Gson gson = new GsonBuilder().create();
                            Msg msg1 = gson.fromJson(reponse, Msg.class);
                            if (msg1.getSuccess()) {
                                ckUtils = new SerialportCkUtils(handler2);
                                ckUtils.openSrialPort();
                                ckUtils.start();
                            } else {
                                ToastUtils.toastUtils(CanyuActivity.this, msg1.getMsg());
                                finish();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /***
     * 驱动轨道-出货
     */
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String strS = msg.getData().getString("strS");
            byte hdhbyte = (byte) num.intValue();
            byte[] bytes = new byte[10];
            bytes[0] = (byte) 0xfa;
            bytes[1] = (byte) 0xfb;
            bytes[2] = 0x06;
            bytes[3] = 0x05;
            bytes[4] = txh;
            bytes[5] = 0x01;
            bytes[6] = 0x01;
            bytes[7] = 0x00;
            bytes[8] = hdhbyte;
            bytes[9] = xor(bytes);
            if (strS.equals("fa fb 41 00 40")) {
                ckUtils.sendSerialPort(bytes);
            } else if (strS.equals("fa fb 42 00 43")) {
                txh++;
                if (txh > 255) {
                    txh = 1;
                }
                SharedPreferences.Editor edit = txhs.edit();
                edit.putInt("txhs", txh);
                edit.commit();

                AisleUtils.pop(type);
                //查询剩余库存
                Integer size = AisleUtils.size(type);
                if(size<=30){
                    sendHttpBh(type,size);
                }
                SerialportCkUtils.flag = false;
                finish();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        Queue.empty();
        new Thread(this).start();
    }

    @Override
    protected void onPause() {
        flag = false;
        Queue.empty();
        super.onPause();
    }

    /***
     * 异或校验算法
     * @param a
     * @return
     */
    public byte xor(byte[] a) {
        byte temp = a[0];
        for (int i = 1; i < a.length - 1; i++) {
            temp ^= a[i];
        }
        return temp;
    }


    /**
     * 补货请求
     * 请求名：weixin/qrfd
     * 发送http请求方法
     */
    private void sendHttpBh(final Integer type, final Integer size) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                String urls = sz.getString("url","https://baiyao.51baiyao.com");
                String urlStr = urls+"/gsm/weixin/jqkcbz";
                //获取机器编号
                String jqbh = sz.getString("name","");
                try {
                    URL url = new URL(urlStr);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestMethod("POST");
                    String jqbhStr = URLEncoder.encode(jqbh, "UTF-8");
                    String paramStr = "jqbh=" + jqbhStr + "&type=" + type + "&size=" + size;
                    OutputStream out = conn.getOutputStream();
                    DataOutputStream dataOut = new DataOutputStream(out);
                    dataOut.writeBytes(paramStr);
                    dataOut.flush();
                    dataOut.close();
                    InputStream in = conn.getInputStream();
                    final String reponse = FilesUtils.readInfo(in);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
